package com.zisuyi.uilibrary.base

import android.os.CountDownTimer
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.weilele.mvvm.base.helper.*
import com.weilele.mvvm.utils.activity.toast
import com.weilele.mvvm.utils.disEnableSystemAnimDurationScale
import com.weilele.mvvm.utils.getCountTimeByLong
import com.yizisu.library.ad.IAdRewardStatus
import com.zisuyi.game.sdk.net.bean.SmallGameInfoBean
import com.zisuyi.uilibrary.GameMessage
import com.zisuyi.uilibrary.R
import com.zisuyi.uilibrary.module.activty.game.holder.GameTimesHolder
import com.zisuyi.uilibrary.module.dialog.SmallGameRewardDialog

/**
 * 小游戏（比如转盘）的基类
 */
abstract class BaseSmallGameActivity<Binding : ViewBinding?> : BaseUiActivity<Binding>() {
    companion object {
        const val GAME_SPIN = "LUCKY_SPIN"
    }

    private val baseUiViewModel: SmallGameViewModel by lazy { getViewModel() }

    private val gameTimesAdapter = lazy { GameTimesHolder.newInstance() }
    private var countDownTimer: CountDownTimer? = null

    val myAd by lazy {
        GameMessage.createAdImpl(
            this,
            isNeedBanner = false,
            isNeedInterstitial = true
        )
    }

    override fun initData() {
        super.initData()
        myAd//初始化广告模块
        disEnableSystemAnimDurationScale(null)
        getGameTimesView()?.adapter = gameTimesAdapter.value
        loadGameInfo()
    }

    private fun loadGameInfo() {
        countDownTimer = null
        getGameTimeDownView()?.text = ""
        baseUiViewModel.loadGameInfo(getGameName())
    }


    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(
            baseUiViewModel.gameInfoData wrapObserver ::onGameInfo
        )
    }

    override fun isNeedSwitchView(): Boolean {
        return true
    }

    /**
     * 当获取到游戏信息
     */
    private fun onGameInfo(value: StatusValue<SmallGameInfoBean>?) {
        when (value) {
            is StatusValue.Error -> {
                showOtherView(value.nonNullMsg, retryText = "RETRY") {
                    loadGameInfo()
                }
            }
            is StatusValue.Running -> {
                showLoadingView()
            }
            is StatusValue.Success -> {
                showContentView()
                refreshAdapter(value.nonNullValue.info)
            }
        }
    }

    /**
     * 刷新游戏次数
     */
    private fun refreshAdapter(value: SmallGameInfoBean.InfoDTO) {
        val max = value.maxCount
        val times = max - value.count
        val isCoolDown = times <= 0
        //取消之前倒计时
        cancelCountDown()
        if (isCoolDown) {
            startCountDown(value.nextTime * 1000)
        } else {
            getGameTimeDownView()?.text = ""
        }
        if (gameTimesAdapter.isInitialized()) {
            val list = mutableListOf<Boolean>()
            repeat(max) {
                list.add(it < times)
            }
            gameTimesAdapter.value.refresh(list,
                { old, new -> old == new },
                { old, new -> old == new })
        }
        onGameInfo(isCoolDown, value.dailyCount < value.maxDailyCount, value)
    }

    /**
     * 开始倒计时
     */
    private fun startCountDown(downTime: Long) {
        val off = downTime - System.currentTimeMillis()
        if (off <= 0) {
            loadGameInfo()
            return
        }
        countDownTimer = object : CountDownTimer(off, 1000) {
            override fun onFinish() {
                loadGameInfo()
            }

            override fun onTick(millisUntilFinished: Long) {
                getGameTimeDownView()?.text = getCountTimeByLong(millisUntilFinished)
            }
        }
        countDownTimer?.start()
    }

    /**
     * 显示游戏弹窗
     */
    fun showRewardDialog() {
        SmallGameRewardDialog.show(
            this,
            getGameName(),
            "REWARD DIAMOND",
            baseUiViewModel.gameInfoData.data?.info?.reward
        )
    }

    /**
     * 展示视频广告
     */
    fun showVideoAd() {
        val isShow = myAd.showVideoAd{
            when (it) {
                IAdRewardStatus.Success -> {
                    baseUiViewModel.addGameTimesByVideoAd(getGameName())
                }
                else -> {
                }
            }
        }
        if (!isShow) {
            getString(R.string.no_ad_hint).toast(Toast.LENGTH_LONG)
        }
    }

    /**
     * 游戏名
     */
    abstract fun getGameName(): String

    /**
     * 游戏次数的view
     */
    abstract fun getGameTimesView(): RecyclerView?

    /**
     * 游戏倒计时的view
     */
    abstract fun getGameTimeDownView(): TextView?

    /**
     * 游戏信息回调
     */
    abstract fun onGameInfo(
        isCoolDown: Boolean/*游戏是否冷却*/,
        enableGame: Boolean/*今天是否已经达到最大游戏次数，是否可以继续游戏*/,
        info: SmallGameInfoBean.InfoDTO
    )

    override fun onResume() {
        super.onResume()
        disEnableSystemAnimDurationScale(null)
    }

    private fun cancelCountDown() {
        countDownTimer?.cancel()
        countDownTimer = null
    }
}